/**
 * \file dmxcon/device.c
 * \author Christian Spoo
 * \date 01.08.2010
 *
 * DMX512 host device handling
 */

#include <errno.h>
#include <malloc.h>
#include <string.h>

#include <dmxcon/device.h>

struct device_t *device_create(void) {
  struct device_t *device = (struct device_t *)malloc(sizeof(struct device_t));
  if (device) {
    memset(device, 0, sizeof(struct device_t));
  }
  return device;
}

int device_destroy(struct device_t *device) {
  if (device) {
    /* If available, destroy device using device driver */
    if (device->ops.destroy)
      return device->ops.destroy(device);

    /* Otherwise, no device driver has been assigned. Manually free the device */
    free(device);
    return 0;
  }

  errno = EINVAL;
  return -1;
}

int device_set_range(struct device_t *device, unsigned short end_addr) {
  if (device) {
    device->end_addr = end_addr;

    if (device->ops.set_range)
      return device->ops.set_range(device, end_addr);

    return 0;
  }

  errno = EINVAL;
  return -1;
}

int device_set_channel(struct device_t *device, unsigned short channel, unsigned char value) {
  if (device) {
    if (device->ops.set_channel)
      return device->ops.set_channel(device, channel, value);      

    errno = ENOENT;
    return -1;
  }

  errno = EINVAL;
  return -1;
}

int device_refresh(struct device_t *device) {
  if (device) {
    if (device->ops.refresh)
      return device->ops.refresh(device);

    return 0;
  }

  errno = EINVAL;
  return -1;
}

